package com.benjaminwan.seriallibrary

import java.io.File
import java.io.FileReader
import java.io.IOException
import java.io.LineNumberReader

class SerialPortFinder {
    companion object {
        private const val TAG: String = "SerialPortFinder"
        private const val DRIVERS_PATH = "/proc/tty/drivers"
    }

    val file = File(DRIVERS_PATH)

    val canRead: Boolean
        get() = file.canRead()

    @Throws(IOException::class)
    private fun getDrivers(): List<SerialDriver> =
        LineNumberReader(FileReader(DRIVERS_PATH))
            .readLines()
            .map { it.split(" +".toRegex()) }
            .filter { it.size >= 5 && it.last() == "serial" }
            .map { SerialDriver(it[0], it[1], it[2], it[3], it[4]) }

    fun getDevices(): List<SerialDevice> =
        try {
            getDrivers().map { driver ->
                driver.findDevices.map {
                    SerialDevice(it.name, it, driver)
                }
            }.flatten().distinctBy { it.file }
        } catch (e: IOException) {
            e.printStackTrace()
            emptyList()
        }


}